import 'dart:io';

import 'package:dio/dio.dart';
import 'package:osc/data/net/dio_util.dart';

class HttpUtils {
  BaseOptions baseOptions;
  Options _options;
  Dio dio;


  HttpUtils(String baseUrl, {ContentType contentType, ResponseType responseType}){
//    baseOptions = getBaseOptions(baseUrl, contentType: contentType, responseType: responseType);
    baseOptions = DioUtil.getBaseOptions();
    _options = DioUtil.getDefOptions();
    baseOptions.baseUrl = baseUrl;
    dio = Dio(baseOptions);
    dio.interceptors.add(DioUtil().cookieManager);
  }

  //getBaseOptions
  static BaseOptions getBaseOptions(String baseUrl, {ContentType contentType, ResponseType responseType}) {
    BaseOptions options = new BaseOptions();
    options.baseUrl = baseUrl;
    options.contentType = contentType;
    options.responseType = responseType;
    options.connectTimeout = 1000 * 50;
    options.receiveTimeout = 1000 * 60;
    return options;
  }

  /// check Options.
  Options _checkOptions(method, options) {
    if (options == null) {
      if(_options == null){
        options = new Options();
      } else {
        options = _options;
      }
    }
    options.method = method;
    return options;
  }

  Future<Response> request(String method, String path,
      {data, queryParameters, CancelToken cancelToken}) async {
    Response response;
    try{
      response = await dio.request(path,
          data: data,
          queryParameters: queryParameters,
          options: _checkOptions(method, _options),
          cancelToken: cancelToken);
    } on DioError catch(err){
      response = err.response;
    }
    _printHttpLog(response);
    return response;
  }

  void _printHttpLog(Response response) {
    try {
      print("----------------Http Log----------------" +
          "\n[statusCode]:   " + response.statusCode.toString() +
          "\n[request   ]:   " + _getOptionsStr(response.request));
      _printDataStr("cookies ", response.request.cookies);
      _printDataStr("reqdata ", response.request.data != null?response.request.data:response.request.queryParameters);
      _printDataStr("response", response.data);
    } catch (ex) {
      print("Http Log" + " error......");
    }
  }

  /// get Options Str.
  String _getOptionsStr(RequestOptions request) {
    return "method: " +
        request.method +
        "  baseUrl: " +
        request.baseUrl +
        "  path: " +
        request.path;
  }

  /// print Data Str.
  void _printDataStr(String tag, Object value) {
    String da = value.toString();
    while (da.isNotEmpty) {
      if (da.length > 512) {
        print("[$tag  ]:   " + da.substring(0, 512));
        da = da.substring(512, da.length);
      } else {
        print("[$tag  ]:   " + da);
        da = "";
      }
    }
  }
}